import requests
import json
import os
from mytools import init_chdir  # NOQA: E402
from mytools import basicClass, getNowTime  # NOQA: E402

# 版本说明： 2023.09.04 优化结构, 2022.08.11 新建，积极封装成可用程序
# 功能说明：
# 备注说明：
# 环境要求： python3 \ windows32or64
# 设备要求：

# 功能需求


class requestsHelper(basicClass):
    # 版本号
    VERSION = 'v0.8 2023.09.04'

    def __init__(self):
        super().__init__()
        self.instanceName = '请求助手(标准版):'
        self.header = {
            "User-Agent":
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36',
            "Content-Type": "application/json; charset=utf-8",
            "accept-encoding": "gzip,deflate",
            "time-stamp": 'nowTimestamp',
            "data-signature": 'dataSignature'
        }

        self.statusCode = {
            200: '成功',
            301: '请求重定向到另外一个接口',
            302: '请求重定向到另外一个接口',
            400: '请求语法错误',
            403: '资源没有访问权限',
            404: '资源不存在（有可能是请求url错误或参数不正确）',
            405: '请求方法不被允许（比如接口只允许Post, 使用Get请求接口）',
            500: '服务器内部错误（通常是服务器挂了或接口Bug)',
            502: '网关失效',
            504: '网关请求超时'
        }

    def printRespStatus(self):
        self.classPrint('返回的状态码', self.response.status_code,
                        self.statusCode[self.response.status_code])
        self.classPrint('编码方式', self.response.encoding)
        self.classPrint('总花费时长', self.response.elapsed.total_seconds())
        # self.classPrint('服务器响应时长', self.response.elapsed.microseconds) 这个只会显示小数点后面的数字，不好用，弃用
        # self.classPrint(self.response.text)



    def testCookie(self):
        s = requests.Session()
        s.get('http://httpbin.org/cookies/set/number/123456789')
        r = s.get('http://httpbin.org/cookies')
        print(r.text)

    def get(self, url=0, **kw):
        try:
            self.response = requests.get(
                url=url, timeout=(1, 2), headers=self.header)
            self.response.raise_for_status()
            self.response.encoding = self.response.apparent_encoding
            self.printRespStatus()
            # print(self.response.text)
            return self.response

        except Exception as e:
            self.classPrint("爬取失败！", e)
            return False


    def setHeader(self, headerMode='chrome'):
        # TODO 设置请求头
        self.classPrint(f'设置请求头')
        header1 = {}

    def setCookie(self, **kw):  # TODO
        cookie = {}
        for key, value in kw.items():
            cookie[key] = value


if __name__ == "__main__":

    # 初始化工作目录
    init_chdir()
    looker = requestsHelper()
    url = 'http://192.168.11.234:81/update/getHmiInfo'
    looker.get(url)
    okJson = json.loads(looker.response.text)
    demo = {
        "loadPwdState": 0,
        "uploadPrjPermit": 0,
        "downloadPwd": 0,
        "ethIP": "192.168.11.234",
        "wifiIP": "0.0.0.0",
        "proName": "",
        "version": "3.37.468.1",
        "hardwareVersion": "HMI-IO-V3.11",
        "projectVersion": "3.37.468.1",
        "OSVersion": "v1.4.13",
        "submodules": {}
    }

    # 工程版本
    print('工程版本= ', okJson['projectVersion'])
    # 固件版本
    print('固件版本= ', okJson['version'])
    print('硬件版本= ', okJson['hardwareVersion'])
